package 设计相邻元素求和服务3242;

public class NeighborSum {
    int[][] arr;
    public NeighborSum(int[][] grid) {
        arr = grid;
    }

    public int adjacentSum(int value) {
        int x, y;
        for (x = 0; x < arr.length; x++) {
            for (y = 0; y < arr.length; y++) {
                if (arr[x][y] == value) {
                    int sum = 0;
                    if(x > 0) {
                        sum += arr[x - 1][y];
                    }
                    if(y > 0) {
                        sum += arr[x][y - 1];
                    }
                    if(x < arr.length - 1) {
                        sum += arr[x + 1][y];
                    }
                    if(y < arr.length - 1) {
                        sum += arr[x][y + 1];
                    }
                    return sum;
                }
            }
        }
        return 0;
    }

    public int diagonalSum(int value) {
        int x = 0, y = 0;
        for (x = 0; x < arr.length; x++) {
            for (y = 0; y < arr.length; y++) {
                if (arr[x][y] == value) {
                    int sum = 0;
                    if(x > 0 && y > 0) {
                        sum += arr[x - 1][y - 1];
                    }
                    if(x > 0 && y < arr.length - 1) {
                        sum += arr[x - 1][y + 1];
                    }
                    if(y > 0 && x < arr.length - 1) {
                        sum += arr[x + 1][y - 1];
                    }
                    if(x < arr.length - 1 && y < arr.length - 1) {
                        sum += arr[x + 1][y + 1];
                    }
                    return sum;
                }
            }
        }
        return 0;
    }
}
